package com.chensheng.service;

import com.chensheng.dao.ProductInfoDAO;
import com.chensheng.enums.ProductStatusEnum;
import com.chensheng.enums.ResultErrorEnum;
import com.chensheng.exception.SellException;
import com.chensheng.model.OrderDetail;
import com.chensheng.model.ProductInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @Author:ChenSheng
 * @Description:
 * @Date: Created in 下午 15:33 2018/5/14 0014
 */
@Service
public class ProductInfoService {

    @Autowired
    private ProductInfoDAO productInfoDAO;

    public List<ProductInfo> findAllInSale(){
        List<ProductInfo> productInfoList = productInfoDAO.selectAllInSale();
        return productInfoList;
    }

    public List<ProductInfo> findAll(Integer start, Integer offset){
        List<ProductInfo> productInfoList = productInfoDAO.selectAll(start, offset);
        return productInfoList;
    }

    public ProductInfo findOne(String productId) {

        ProductInfo productInfo = productInfoDAO.selectByProductId(productId);

        return productInfo;
    }

    public void decreaseStock(Integer reduction, String productId) {
        productInfoDAO.decreaseStock(reduction, productId);
    }

    public void increaseStock(List<OrderDetail> orderDetailList) {
        for (OrderDetail orderDetail : orderDetailList){
            productInfoDAO.increaseStock(orderDetail.getProductId(), orderDetail.getProductQuantity());
        }
    }

    public Integer count() {
        return productInfoDAO.count();
    }

    public void off_sale(String productId) {
        ProductInfo productInfo = productInfoDAO.selectByProductId(productId);
        if(ObjectUtils.isEmpty(productInfo)) {
            throw new SellException(ResultErrorEnum.PRODUCT_NOT_EXIST_ERROR);
        }
        if(productInfo.getProductStatus().equals(ProductStatusEnum.DOWN.getCode())){
            throw new SellException(ResultErrorEnum.PRODUCT_STATUS_ERROR);
        }

        productInfoDAO.setProductStatus(ProductStatusEnum.DOWN.getCode(), productId);
    }

    public void on_sale(String productId) {
        ProductInfo productInfo = productInfoDAO.selectByProductId(productId);
        if(ObjectUtils.isEmpty(productInfo)) {
            throw new SellException(ResultErrorEnum.PRODUCT_NOT_EXIST_ERROR);
        }
        if(!productInfo.getProductStatus().equals(ProductStatusEnum.DOWN.getCode())){
            throw new SellException(ResultErrorEnum.PRODUCT_STATUS_ERROR);
        }

        productInfoDAO.setProductStatus(ProductStatusEnum.UP.getCode(), productId);
    }

    public void save(ProductInfo productInfo) {
        productInfoDAO.insertOne(productInfo);
    }

    public void update(ProductInfo productInfo){
        productInfoDAO.updateOne(productInfo);
    }
}
